import express, { Handler } from "express";
import swaggerUi from "swagger-ui-express";
// @ts-ignore
import swaggerJSDoc from "swagger-jsdoc";
import swaggerConfig from "./swagger/config";
import routes from "./routes";
import AppDataSource from "./data-source";
import bodyParser from "body-parser";
import cors from "cors";

AppDataSource.initialize()
  .then(async (res) => {
    console.log("connect success");
    const app = express();
    const port = process.env.PORT || 3000;

    // 全局允许跨域
    app.use(cors());

    app.use(bodyParser.json());

    // Swagger setup
    const swaggerDocs = swaggerJSDoc(swaggerConfig);
    const middlewares: Handler[] = [
      swaggerUi.serve as unknown as Handler,
      swaggerUi.setup(swaggerDocs) as unknown as Handler,
    ];

    app.use("/api-docs", ...middlewares);

    // 注册路由
    app.use("/api", routes);

    app.listen(port, () => {
      console.log(`[server]: Server is running at http://localhost:${port}`);
    });
  })
  .catch((err) => {
    console.log("connect fail", err);
  });
